<template>
  <a-modal
    v-model:open="state.dialog.isShowDialog"
    :title="state.dialog.title"
    @ok="handleSubmit"
    @cancel="handleReset"
    :width="620"
    centered
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 4 }"
    >
      <a-form-item label="指标名称" name="name" required>
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="key_name" name="keyName" required>
        <a-input v-model:value="formState.keyName" />
      </a-form-item>
      <a-form-item label="同义词" name="synonyms">
        <a-textarea
          v-model:value="formState.synonyms"
          placeholder="请输入逗号分隔的同义词，如：a,b"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="指标定义" name="definition">
        <a-textarea
          v-model:value="formState.definition"
          allow-clear
          :maxlength="100"
          placeholder="内容不能超过100字"
        />
      </a-form-item>
      <a-form-item label="计算公式" name="calculationMethod">
        <a-textarea
          v-model:value="formState.calculationMethod"
          allow-clear
          :maxlength="100"
          placeholder="内容不能超过100字"
        />
      </a-form-item>
      <a-form-item label="关联指标">
        <div>
          <a-table
            :columns="columns"
            :data-source="formState.relatedMetrics"
            :row-key="(record: any) => record.key"
            size="small"
            bordered
            :pagination="false"
          >
            <template #headerCell="{ column }">
              <span>{{ column.title }}</span>
            </template>
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'metricsName'">
                <a-select
                  v-model:value="record.metricsName"
                  :placeholder="`请选择${column.title}`"
                  :options="
                    [...Array(25)].map((_, i) => ({
                      value: (i + 10).toString(36) + (i + 1),
                    }))
                  "
                ></a-select>
              </template>
              <template v-else-if="column.dataIndex === 'metricsRelation'">
                <a-select
                  v-model:value="record.metricsRelation"
                  :placeholder="`请选择${column.title}`"
                  mode="multiple"
                  :options="
                    [...Array(25)].map((_, i) => ({
                      value: (i + 10).toString(36) + (i + 1),
                    }))
                  "
                ></a-select>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button danger type="text" @click="deleteRow(record.key)">
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
        <a class="text-[#1677ff]" @click="addRow">
          <PlusOutlined class="mr-[5px]" />新增关联
        </a>
      </a-form-item>
      <a-form-item label="适用维度" name="applicableDimensions">
        <a-select
          v-model:value="formState.applicableDimensions"
          mode="multiple"
          placeholder="Please select"
          :options="
            [...Array(25)].map((_, i) => ({
              value: (i + 10).toString(36) + (i + 1),
            }))
          "
        ></a-select>
      </a-form-item>
      <a-form-item label="关联维度" name="relatedDimensions">
        <a-select
          v-model:value="formState.relatedDimensions"
          mode="multiple"
          placeholder="Please select"
          :options="
            [...Array(25)].map((_, i) => ({
              value: (i + 10).toString(36) + (i + 1),
            }))
          "
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, reactive, defineAsyncComponent } from 'vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { PlusOutlined } from '@ant-design/icons-vue';

  import { MetricsFormState, InitRelationItem } from '@/types/metrics';

  const emit = defineEmits(['refresh']);

  const formRef = ref();
  const columns = reactive([
    {
      title: '指标名称',
      dataIndex: 'metricsName',
      key: 'metricsName',
    },
    {
      title: '指标关系',
      dataIndex: 'metricsRelation',
      key: 'metricsRelation',
    },
    { title: '操作', key: 'action' },
  ]);
  // 获取默认参数配置
  const getDefaultRelation = (): InitRelationItem => ({
    key: `relation-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, // 唯一标识
    metricsName: '',
    metricsRelation: [],
  });
  const metricsForm = [getDefaultRelation()];

  const state = reactive({
    dialog: {
      isShowDialog: false,
      title: '新增指标',
    },
  });
  const formState = reactive<MetricsFormState>({
    relatedMetrics: [
      {
        metricsName: '', //为undefined时会显示placeholder
        metricsRelation: [],
        key: `relation-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      },
    ],
  });

  const validateCommaSeparated = (_rule: Rule, value: string) => {
    if (value && value.length > 100) {
      return Promise.reject('输入内容不能超过100字');
    }
    if (value && !/^[\u4e00-\u9fa5a-zA-Z0-9,，\s]+$/.test(value)) {
      return Promise.reject('请使用逗号分隔内容');
    }
    return Promise.resolve();
  };
  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, message: '请输入维度名称', trigger: 'blur' },
      { min: 2, max: 20, trigger: 'blur', message: '请输入2-20个字符' },
    ],
    keyName: [
      { required: true, message: '请输入key_name', trigger: 'blur' },
      { min: 2, max: 20, trigger: 'blur', message: '请输入2-20个字符' },
    ],
    synonyms: [{ validator: validateCommaSeparated, trigger: 'blur' }],
  };

  const openDialog = () => {
    state.dialog.isShowDialog = true;
  };

  // 提交处理[5](@ref)
  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      console.log('提交数据:', formState);
      // 调用API接口提交数据
      state.dialog.isShowDialog = false;
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 重置表单
  const handleReset = () => {
    formRef.value.resetFields();
    state.dialog.isShowDialog = false;
  };

  // 新增行方法
  const addRow = () => {
    const newParam: InitRelationItem = {
      key: `relation-${Date.now()}`,
      metricsName: '',
      metricsRelation: [],
    };

    formState.relatedMetrics?.push(newParam);
  };

  // 删除行方法
  const deleteRow = (key: string) => {
    formState.relatedMetrics = formState.relatedMetrics?.filter(
      (item) => item.key !== key,
    );
  };

  // 暴露变量
  defineExpose({
    openDialog,
  });
</script>

<style scoped>
  .ant-form-item {
    margin-bottom: 10px;
  }
</style>
